package dnl.util.ui.actions;

import java.util.HashMap;

import javax.swing.Action;
import javax.swing.ImageIcon;


/**
  * A generic action manager that may be used or subclassed by GUI applications.
  * 
  * @author Daniel Or
  * @version 1.0
  */
public class ActionManager {
	HashMap<String, ActionGroup> allGroups = new HashMap<String, ActionGroup>();
	
	/* a Map of all actions */
	protected HashMap<String, Action> allActions = new HashMap<String, Action>();
	
	/**
	 * 
	 * @param name
	 * @param enabled
	 */
	public void setMenuEnabled(String name, boolean enabled){
		ActionGroup ag = getGroup(name);
		if(ag != null)
			ag.setEnabled(enabled);
	}
	
	/**
	 * 
	 * @param group
	 * @param item
	 * @param enabled
	 */
	public void setItemEnabled(String group, String item, boolean enabled){
		ActionGroup ag = getGroup(group);
		if(ag == null)
			return;
		ag.setItemEnabled(item, enabled);	
	}
	
	/**
	 * 
	 * @param name
	 * @return Action
	 */
	public Action getAction(String name){
		return allActions.get(name);
	}
	
	/**
	 * 
	 * @param name
	 * @return Action
	 */
	public ManagedAction getManagedAction(String name){
		return (ManagedAction)allActions.get(name);
	}	
	
	/**
	 * 
	 * @param name
	 * @return HashMap
	 */
	protected ActionGroup getGroup(String name){
		synchronized(allGroups){
			ActionGroup group = null;
			Object obj = allGroups.get(name);
			if(obj == null){
				group = new ActionGroup(name);
				allGroups.put(name, group);
			}
			else 
				group = (ActionGroup)obj;
			return group;				
		}
	}
	
	/** 
	  * The only difference from AbstractAction is that every new Instance
	  * is automatically registeres to this manager. 
	  * 
	  * @author Daniel Or
	  * @version 1.0
	  */
	public abstract class ManagedAction extends AbstractAction {
	  /**
	   * Creates a new AbstractAction object.
	   */
	  public ManagedAction(String name) {
	    super(name);
	    ActionManager.this.allActions.put(name, this);
	  }
	  
	  public ManagedAction(String name, boolean threaded) {
	    super(name, threaded);
	    ActionManager.this.allActions.put(name, this);
	  }
	
	  public ManagedAction(String name, ImageIcon icon, boolean threaded) {
	    super(name, icon, threaded);
	    ActionManager.this.allActions.put(name, this);
	  }		
	}
	
}
